package part2Project;

import java.io.*;
import java.util.Iterator;

public class PLYWriter
{
	public static void writeFile(ArgumentParser arg, HalfEdgeScheme hes) throws Exception
	{
		int vertices = hes.numVertices();
		//int edges = hes.numEdges();
		
		StringBuffer f = new StringBuffer("");
		
		for(Iterator<HalfEdge> ie = hes.edgeIterator(); ie.hasNext(); )
		{
			HalfEdge e = ie.next();
			if(!e.face().printed)
			{
				f.append(e.face().toString(e) + "\n");
				e.face().printed = true;
			}
		}
		
		BufferedWriter out = new BufferedWriter(new FileWriter(arg.getOutputFile()));		
		
		int faces = Face.numFaces;					// Only know this after printing/tessellating the faces
		out.write(header(vertices, faces, arg));	// So need to print faces before writing header
		
		for(Iterator<Vertex> iv = hes.vertexIterator(); iv.hasNext(); )
		{
			out.write(iv.next().toString() + "\n");
		}		
		
		out.write(f.toString());
		
		out.close();
	}
	
	private static String header(int vertices, int faces, ArgumentParser arg)
	{
		return new String("" +
				"ply\n" +
				"format ascii 1.0\n" +
				"comment Generated by Daniel Bates's Part II Project\n" +
				"comment Using "+(arg.isAdaptive()?"":"non-")+"adaptive algorithm\n" +
				"comment Subdivision steps: " + arg.getNumSteps() + "\n" +
				"comment Degree of smoothness: " + arg.getDegree() + "\n" +
				"element vertex " + vertices + "\n" +
				"property float32 x\n" +
				"property float32 y\n" +
				"property float32 z\n" +
				"element face " + faces + "\n" +
				"property list uint8 int32 vertex_index\n" +
				"end_header\n");
	}
}
